import type { TokenInfo } from "./token-info";
import { String } from "../utils/string";

export class UserInfo {
  tokenInfo: TokenInfo;
  timeStamp: number;
  userName: string;

  constructor(tokenInfo: TokenInfo) {
    this.userName = this.getUserName(tokenInfo.access_token);
    this.timeStamp = Date.now();
    this.tokenInfo = tokenInfo;
  }

  private getUserName(token: string): string {
    const values = token.split(".");
    const jsonString = atob(values[1]);
    const userName = JSON.parse(jsonString).given_name;
    if (String.isNullOrWhitespace(userName)) {
      return "";
    }

    return userName;
  }

  // 令牌是否过期
  public isExpired() {
    const isValid =
      this.tokenInfo.expires_in - (Date.now() - this.timeStamp) / 1000 > 5;
    return !isValid;
  }

  // 获取刷新令牌
  public getRefreshToken() {
    return this.tokenInfo.refresh_token;
  }

  // 获取访问令牌
  public getAccessToken() {
    return this.tokenInfo.token_type + " " + this.tokenInfo.access_token;
  }
}
